package com.zzdzz.fileencryption.controller;

import com.zzdzz.fileencryption.service.FileEncryptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件加密控制层
 */
@RestController
@RequestMapping("/api")
public class FileEncryptionController {

    @Autowired
    private final FileEncryptionService fileEncryptionService;

    public FileEncryptionController(FileEncryptionService fileEncryptionService) {
        this.fileEncryptionService = fileEncryptionService;
    }


    /**
     * 加密文件
     * @param file 待加密的文件
     * @return 加密后的文件数据
     * @throws IOException
     */
    @PostMapping("/files/encrypt")
    public ResponseEntity<byte[]> encryptFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 调用Service层进行加密处理
        byte[] processedData = fileEncryptionService.processFile(file, true);
        String originalFilename = file.getOriginalFilename();
        String newFilename = fileEncryptionService.generateNewFilename(originalFilename, true);

        // 设置响应头
        HttpHeaders headers = fileEncryptionService.createResponseHeaders(newFilename);

        return new ResponseEntity<>(processedData, headers, HttpStatus.OK);
    }

    /**
     * 解密文件
     * @param file 待解密的文件
     * @return 解密后的文件数据
     * @throws IOException
     */
    @PostMapping("/files/decrypt")
    public ResponseEntity<byte[]> decryptFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 调用Service层进行解密处理
        byte[] processedData = fileEncryptionService.processFile(file, false);
        String originalFilename = file.getOriginalFilename();
        String newFilename = fileEncryptionService.generateNewFilename(originalFilename, false);

        // 设置响应头
        HttpHeaders headers = fileEncryptionService.createResponseHeaders(newFilename);

        return new ResponseEntity<>(processedData, headers, HttpStatus.OK);
    }
}

